package com.atguigu.gmall.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.constant.RedisConst;
import com.atguigu.gmall.entity.UserAddress;
import com.atguigu.gmall.entity.UserInfo;
import com.atguigu.gmall.result.RetVal;
import com.atguigu.gmall.service.UserAddressService;
import com.atguigu.gmall.service.UserService;
import com.atguigu.gmall.util.IpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public RetVal login(@RequestBody UserInfo userInfoParams, HttpServletRequest request) {
        UserInfo userInfo = userService.queryUserByUserLoginParams(userInfoParams);
        if (ObjectUtils.isEmpty(userInfo)) //查询不到数据，或密码出错
            return RetVal.fail();
        HashMap<String, Object> retMap = new HashMap<>(); //1.返回给页面信息的map
        String token = UUID.randomUUID().toString();   //2.制作一个token
        retMap.put("token", token);
        retMap.put("nickName", userInfo.getNickName());//3.把用户昵称信息也放入
        String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;   //4.将用户信息存储缓存！
        JSONObject loginInfo = new JSONObject();    //5.userId用于判断是否登录,ip地址用于判断是否为同一台电脑登录
        loginInfo.put("userId", userInfo.getId().toString());
        loginInfo.put("loginIp", IpUtil.getIpAddress(request));
        redisTemplate.opsForValue().set(userKey, loginInfo.toJSONString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
        return RetVal.ok(retMap);
    }

    @GetMapping("logout")
    public RetVal logout(HttpServletRequest request) {
        String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + request.getHeader("token");
        redisTemplate.delete(userKey); //删除reids 的 key
        return RetVal.ok();
    }

    //根据用户的id获取用户的地址列表
    @GetMapping("getUserAddressByUserId/{userId}")
    public List<UserAddress> getUserAddressByUserId(@PathVariable String userId) {
        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return userAddressService.list(queryWrapper);
    }

}
